#!/usr/bin/python

# Client for EveryDNS dynamic DNS service
#
# (C) 2008 Paolo Venturi <venturi.paolo at gmail.com>
# Released under the terms of the GNU General Public License.
#
# Inspired by eDNS.pl and so thanks to its authors.
#
# To supporto Python 3.x switch the comments marked 2.x and 3.x
# Any comment appreciated, expecially on how to make a better
# compatibility code between 2.x and 3.x Python
#
# EveryDNS: http://www.everydns.com/
# eDNS.pl: http://www.everydns.net/eDNS.pl
# Slitaz: http://www.slitaz.org/ (a very nice linux distribution !)

from optparse import OptionParser
import base64
import urllib2         # Python 2.x
#import urllib.request # Python 3.x

usage = "usage: %prog [options] username password"
version = "0.1"
description = "EveryDNS client. Minimum parameters required are username and password of your registration at EveryDNS"
target = "dyn.everydns.net"

parser = OptionParser(usage=usage, version=version, description=description)
parser.add_option("-d", "--domain",
    dest="domainName", help="your dynamic domain name. If absent EveryDNS.net use your username/password to find it.")
parser.add_option("-a", "--address",
    dest="address", help="the ip address your domain will have. If absent EveryDNS.net use the address of this request." +
    " If you are under a firewall probably you have to use it.")

(options, args) = parser.parse_args()

if len(args) != 2:
    parser.error("Incorrect number of arguments. Both username and password are needed")

authorization = base64.b64encode(args[0] + ":" + args[1])                                    # Python 2.x
#authorization = base64.b64encode((args[0] + ":" + args[1]).encode("ascii")).decode("ascii") # Python 3.x

url = "http://" + target + "/index.php?ver=" + version

if options.domainName != None:
    url = url + "&domain=" + options.domainName
if options.address != None:
    url = url + "&ip=" + options.address

request = urllib2.Request(url)         # Python 2.x
#request = urllib.request.Request(url) # Python 3.x
request.add_header("User-Agent", "eDNS.py " + version)
request.add_header("Host", target)
request.add_header("Authorization", "Basic " + authorization)

response = urllib2.urlopen(request)         # Python 2.x
#response = urllib.request.urlopen(request) # Python 3.x

exitCode = 2
while 1:
    line = response.readline()                  # Python 2.x
    #line = response.readline().decode("ascii") # Python 3.x
    if not line: break
    if line.startswith("Exit code: "):
        exitCode = int(line[11:])
    print(line)

exit(exitCode)
